/*** server ***/
package comm;

import db.DataBase;
import main.Escrow;
import main.EscrowJournal;

public class KnockKnockProtocol {

    public static int contador = 0;
    public static final int INF = 999999999;
    public static EscrowJournal[] journal = new EscrowJournal[100];

    public String processInput(String theInput) {
        String theOutput = null;


        if (theInput.equalsIgnoreCase("req")) {
            theOutput = "ack";
        }

        if (theInput.equalsIgnoreCase("read_lock")) {
            theOutput = "success";
        }

        if (theInput.equalsIgnoreCase("write_lock")) {
            theOutput = "success";
        }

        if (theInput.equalsIgnoreCase("header")) {
            String[] row = Stock.getHeaders();
            theOutput = row[0] + " | " + row[1] + " | " + row[2] + " | " + row[3] + " | " + row[4];
        }

        if (theInput.equalsIgnoreCase("table")) {
            String[] row1 = DataBase.readData(0, "8", DataBase.PRODUCTS);
            theOutput = row1[0] + " | " + row1[1] + " | " + row1[2] + " | " + row1[3] + " | " + row1[4] + " | " + row1[5] + " | " + row1[6] + " | " + row1[7];
        }

        if (theInput.equalsIgnoreCase("bye")) {
            main.Main.setState(0);
            theOutput = "Bye.";
        }

        /* String esperada:
         * ESCROW#ID#QTD#TEST#RECOVER#TIMESTAMP
         */
        if (theInput.toUpperCase().startsWith("ESCROW")) {
            //vetor de Strings com cada substring de ESCROW#ID#QTD#TEST#RECOVER
            String[] row2 = theInput.split("#");
            //Verifica se QTD e TEST foram lidos
            if (row2[3] != null) {
                String comparativo = row2[3].substring(0, 1); // se eh > ou <
                row2[2] = row2[2].substring(1); // tira o + ou -
                row2[3] = row2[3].substring(1); // tira o > ou <
                int id = Integer.parseInt(row2[1]);
                int qtd = Integer.parseInt(row2[2]);
                int limite = Integer.parseInt(row2[3]);
                if (comparativo.equalsIgnoreCase("<")) {
                    if (Escrow.reservenegativeProduct(id, qtd)) {
                        theOutput = "TS" + contador;
                        if (journal[contador] == null) {
                            journal[contador] = new EscrowJournal();
                            DataBase.setTimestamp(row2[1], row2[5]);
                        }
                        journal[contador].setData(contador, -INF, limite, -qtd, 0, id);
                    } else {
                        theOutput = "Fail";
                    }
                } else if (comparativo.equalsIgnoreCase(">")) {
                    if (Escrow.reserveProduct(id, qtd)) {
                        theOutput = "TS" + contador;
                        if (journal[contador] == null) {
                            journal[contador] = new EscrowJournal();
                            DataBase.setTimestamp(row2[1], row2[5]);
                        }
                        journal[contador].setData(contador, limite, INF, qtd, 0, id);
                    } else {
                        System.out.println("ESTOQUE INSUFICIENTE!!!");
                        theOutput = "Fail";
                    }
                } else {
                    theOutput = "Fail";
                }
            } else {
                theOutput = "Fail";
            }
        } // Fim do teste para ESCROW#ID#QTD#TEST#RECOVER#TIMESTAMP

        /* String esperada:
         * USE#ID#QTD
         */
        if (theInput.toUpperCase().startsWith("USE")) {
            String[] use = theInput.split("#");
            int qtd;
            if (use[2].charAt(0) == '+') {
                qtd = Integer.parseInt(use[2].substring(1));
            } else {
                qtd = Integer.parseInt(use[2]);
            }
            journal[contador].setUse(qtd);
            contador++;
            theOutput = "ACK";
        }
        //COMMITID
        if (theInput.toUpperCase().startsWith("COMMIT")) {
            theInput = theInput.substring(6);
            int indice = Integer.parseInt(theInput);
            int qtd = journal[indice].getUse();
            int id = journal[indice].getId();
            if (qtd >= 0) {
                Escrow.sellReservedProduct(id, qtd);
            } else {
                Escrow.sellReservednegativeProduct(id, qtd);
            }
            journal[indice].deleteJournal();
            theOutput = "ACK";
        }
        //ABORTID
        if (theInput.toUpperCase().startsWith("ABORT")) {
            theInput = theInput.substring(6);
            int indice = Integer.parseInt(theInput);
            journal[indice].deleteJournal();
            theOutput = "ACK";
        }
        //PRODUTO#ID
        if (theInput.toUpperCase().startsWith("PRODUTO")) {
            String[] row4 = theInput.split("#");
            String[] row5 = DataBase.readData(0, row4[1], 1);
            theOutput = row5[0] + "#" + row5[1] + "#" + row5[2] + "#" + row5[3] + "#" + row5[4] + "#" + row5[5] + "#" + row5[6] + "#" + row5[7];
        }

        trace(theOutput);

        return theOutput;
    }

    public static void trace(String s) {
        System.err.println("KnockKnockProtocol > " + s);
    }
}
